package cn.cas.mango.util.paramCheck;

import cn.cas.mango.dto.param.Param;
import co.elastic.clients.elasticsearch._types.FieldValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ParamCheckUtil {
  public static List<FieldValue> string2FieldValue(String string) {
    String[] split = string.split(",");
    List<FieldValue> ret = new ArrayList<>();
    for (String s : split) {
      ret.add(FieldValue.of(s.trim()));
    }
    return ret;
  }

  public static String checkParam(Param formData) {
    String isSuccess = "ok";
    if (formData.getCurrentPage() == null || formData.getCurrentPage() <= 0) {
      formData.setCurrentPage(1);
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
      if (Strings.isNotBlank(formData.getEndDate())) {
        formData.setEndDate(sdf.format(sdf.parse(formData.getEndDate())));
      }
      if (Strings.isNotBlank(formData.getStartDate())) {
        formData.setStartDate(sdf.format(sdf.parse(formData.getStartDate())));
      }
    } catch (Exception e) {
      String info = "参数[endDate或startDate]非法，格式应为'yyyy-MM-dd'";
      log.info(info);
      isSuccess = info;
      return isSuccess;
    }

    //WebSiteType可为空，多个值使用逗号隔开
    if (Strings.isNotBlank(formData.getWebSiteType())) {
      formData.setWebSiteTypeArray(string2FieldValue(formData.getWebSiteType()));
    }
    //webSites可为空，多个值逗号隔开
    if (Strings.isNotBlank(formData.getWebSites())) {
      formData.setWebSitesArray(string2FieldValue(formData.getWebSites()));
    }
    return isSuccess;
  }
}
